<template>
  <div class="tag-manager-container" :style="{ '--local-mount-height': cssVar ? `var(${cssVar})` : '100%' }">
    <!-- 筛选和操作区域 -->
    <div class="filter-section">
      <el-row class="mb10" :gutter=10>
        <el-col  :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-select
            v-model="state.selectedGroup"
            :placeholder="$t('message.tag.group')"
            clearable
            filterable
            size="default"
            style="width: 100%"
            @change="handleGroupFilterChange"
          >
            <el-option
              v-for="group in state.groupOptions"
              :key="group.value"
              :label="group.label"
              :value="group.value"
            />
          </el-select>
        </el-col>
        <el-col :gutter=5 :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-select
            v-model="state.selectedName"
            :placeholder="$t('message.tag.name')"
            clearable
            filterable
            size="default"
            style="width: 100%"
            :disabled="!state.selectedGroup"
            @change="handleNameFilterChange"
          >
            <el-option
              v-for="name in filteredNameOptions"
              :key="name.value"
              :label="name.label"
              :value="name.value"
            />
          </el-select>
        </el-col>
        <el-col :gutter=5 :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-input v-model="state.description" @keyup.enter.native="fetchTags"
            :placeholder="$t('message.tag.description')" clearable size="default">
            <template #prefix>
              <el-icon>
                <Document />
              </el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
      <el-row>
        <div style="display: flex;gap: 10px;">
          <el-button size="default" type="primary" @click="fetchTags" icon="Search" class="search-btn">{{ $t('message.common.search') }}</el-button>
          <el-button type="primary" size="default" @click="handleExport">{{ $t('message.common.exportAsCsv') }}</el-button>
          <el-upload
            :show-file-list="false"
            accept=".csv"
            :before-upload="handleImport"
            class="upload-btn"
          >
            <el-button size="default" type="success">{{ $t('message.common.importCsv') }}</el-button>
          </el-upload>
          <el-button size="default" type="danger" @click="deleteFilter" icon="Search" class="search-btn">{{ $t('message.common.deleteFilter') }}</el-button>
          <el-button size="default" type="success" @click="handleAddTag" icon="Plus" circle class="add-btn"></el-button>
          <el-pagination size="default" background :current-page="state.pagination.current"
            :page-size="state.pagination.size" :total="state.pagination.total" :pager-count="5"
            :page-sizes="[10, 20, 30]" @current-change="handlePageChange" @size-change="handleSizeChange"
            layout="total, sizes, prev, pager, next, jumper" />
        </div>
      </el-row>
    </div>

    <!-- 标签卡片区域 -->
    <div class="tags-container">
      <div v-if="state.tags.length === 0" class="empty-state">
        <el-empty description="没有找到标签" :image-size="200">
          <el-button type="primary" @click="handleAddTag">创建新标签</el-button>
        </el-empty>
      </div>

      <div v-else class="tags-grid custom-scrollbar">
        <div v-for="tag in state.tags" :key="tag.groupId+tag.value" class="tag-card" @contextmenu.prevent="onContextmenu(tag, $event)">
          <div class="tag-header">
            <span class="tag-group">{{ tag.group }}</span>
            <span class="tag-divider">/</span>
            <span class="tag-name">{{ tag.name }}</span>
          </div>
          <div class="tag-content">
            <div class="tag-value">
              <el-icon class="value-icon">
                <Key />
              </el-icon>
              <span>{{ tag.value }}</span>
            </div>
            <div class="tag-label">
              <el-icon class="label-icon">
                <Comment />
              </el-icon>
              <span>{{ tag.label }}</span>
            </div>
          </div>
          <div class="tag-actions">
            <el-tooltip content="编辑" placement="top">
              <el-button size="default" circle @click.stop="handleEdit(tag)">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="复制" placement="top">
              <el-button size="default" circle @click.stop="handleCopy(tag)">
                <el-icon>
                  <DocumentCopy />
                </el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="default" circle type="danger" @click.stop="handleDelete(tag)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <Contextmenu ref="contextmenuRef" :menu-items="state.customMenuItems" :dropdown="state.dropdown"
      @current-contextmenu-click="onCurrentContextmenuClick" />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" append-to-body width="600px">
      <el-form :model="state.currentTag" label-width="100px" label-position="top" ref="tagForm">
        <!-- 分组选择区域 -->
        <el-form-item label="一级分类" prop="group">
          <div class="category-selector">
            <el-select
              v-model="state.currentTag.group"
              placeholder="选择一级分类"
              clearable
              filterable
              style="width: 100%"
              @change="handleGroupChange"
            >
              <el-option
                v-for="group in state.groupOptions"
                :key="group.value"
                :label="group.label"
                :value="group.value"
              />
            </el-select>

            <el-button
              size="default"
              type="primary"
              @click="showNewGroupInput = true"
              class="add-category-btn"
            >
              <el-icon><Plus /></el-icon> 新增一级分类
            </el-button>
          </div>

          <!-- 新增一级分类输入框 -->
          <div v-if="showNewGroupInput" class="new-category-input">
            <el-input
              v-model="newGroupName"
              placeholder="输入新的一级分类名称"
              size="default"
              @keyup.enter="addNewGroup"
            />
            <div class="input-actions">
              <el-button size="default" @click="addNewGroup">确认</el-button>
              <el-button size="default" type="text" @click="showNewGroupInput = false">取消</el-button>
            </div>
            <p v-if="groupValidationMessage" class="validation-message">{{ groupValidationMessage }}</p>
          </div>
        </el-form-item>

        <!-- 二级分类选择区域 -->
        <el-form-item label="二级分类" prop="name" :disabled="!state.currentTag.group">
          <div class="category-selector">
            <el-select
              v-model="state.currentTag.name"
              placeholder="选择二级分类"
              clearable
              filterable
              style="width: 100%"
              :disabled="!state.currentTag.group"
            >
              <el-option
                v-for="name in filteredDialogNameOptions"
                :key="name.value"
                :label="name.label"
                :value="name.value"
              />
            </el-select>

            <el-button
              size="default"
              type="primary"
              @click="showNewNameInput = true"
              :disabled="!state.currentTag.group"
              class="add-category-btn"
            >
              <el-icon><Plus /></el-icon> 新增二级分类
            </el-button>
          </div>

          <!-- 新增二级分类输入框 -->
          <div v-if="showNewNameInput" class="new-category-input">
            <el-input
              v-model="newName"
              placeholder="输入新的二级分类名称"
              size="default"
              @keyup.enter="addNewName"
            />
            <div class="input-actions">
              <el-button size="default" @click="addNewName">确认</el-button>
              <el-button size="default" type="text" @click="showNewNameInput = false">取消</el-button>
            </div>
            <p v-if="nameValidationMessage" class="validation-message">{{ nameValidationMessage }}</p>
          </div>
        </el-form-item>

        <el-form-item label="标签值" prop="value">
          <el-input v-model="state.currentTag.value" placeholder="请输入标签值" />
        </el-form-item>
        <el-form-item label="描述" prop="label">
          <el-input v-model="state.currentTag.label" type="textarea" :rows="3" resize="none" placeholder="请输入标签描述信息"
            maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="state.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTag">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导出进度对话框 -->
    <el-dialog
      v-model="taskStatus.progressVisible"
      :title="`${taskStatus.type === 'import' ? '导入' : '导出'}进度`"
      width="300px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="task-progress">
        <el-progress
          :percentage="taskStatus.progress"
          stroke-width="6"
          :status="taskStatus.progress === 100 ? 'success' : 'active'"
        />
        <p class="progress-text">{{ taskStatus.progress }}%</p>
        <p v-if="taskStatus.progress < 100" class="progress-info">
          正在{{ taskStatus.type === 'import' ? '导入' : '导出' }}数据，请稍候...
        </p>
        <p v-if="taskStatus.progress === 100" class="progress-info">
          {{ taskStatus.type === 'import' ? '导入' : '导出' }}完成
          <span v-if="taskStatus.type === 'export'">，即将下载文件</span>
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="TagPanel">
import { reactive, ref, onMounted, computed, watch, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import Contextmenu from '@renderer/views/common/component/contextmenu.vue'
import { tagApi } from '@renderer/api/tags'
import { translateApi } from '@renderer/api/translate'

const instance = getCurrentInstance();
const cssVar = instance?.appContext.config.globalProperties.$cssVarName;

// 类型定义
interface Category {
  group: string;
  name: string;
}

interface GroupOption {
  value: string;
  label: string;
}

interface NameOption {
  value: string;
  label: string;
  group: string;
}

interface Tag {
  type: 'add'|'edit'
  groupId:string
  group: string
  name: string
  value: string
  label: string
  oldTag: string
}

interface MenuItem {
  id: string
  txt: string
  icon: string
  action: 'edit' | 'delete' | 'add' | 'copy'
}

const contextmenuRef = ref()
const tagForm = ref<InstanceType<typeof ElForm>>()

// 对话框中新增分类的状态管理
const showNewGroupInput = ref(false)
const showNewNameInput = ref(false)
const newGroupName = ref('')
const newName = ref('')
const groupValidationMessage = ref('')
const nameValidationMessage = ref('')

const state = reactive({
  // 数据相关
  groupOptions: [] as GroupOption[],
  nameOptions: [] as NameOption[],
  selectedGroup: '',
  selectedName: '',
  tag: '',
  description: '',
  tags: [] as Tag[],

  // 当前编辑/新增的标签
  currentTag: {
    type: 'add',
    group: '',
    name: '',
    value: '',
    label: '',
    groupId: '',
    oldTag: ''
  } as Partial<Tag>,

  // 分页相关
  pagination: {
    current: 1,
    size: 20,
    total: 0
  },

  // 对话框相关
  dialogVisible: false,
  dialogTitle: '',

  // 右键菜单相关
  dropdown: { x: 0, y: 0 },
  customMenuItems: [
    { id: 'edit', txt: '编辑标签', icon: 'ele-Edit', action: 'edit' },
    { id: 'delete', txt: '删除标签', icon: 'ele-Delete', action: 'delete' },
    { id: 'add', txt: '新增标签', icon: 'ele-CirclePlus', action: 'add' },
    { id: 'copy', txt: '复制标签', icon: 'ele-DocumentCopy', action: 'copy' }
  ] as MenuItem[]
})

const taskStatus = reactive({
  type: 'import' as 'import' | 'export', // 任务类型：导入/导出
  loading: false, // 任务加载状态
  progressVisible: false, // 进度对话框显示状态
  progress: 0, // 进度百分比
  taskId: '', // 当前任务ID
  progressTimer: null as NodeJS.Timeout | null // 进度查询定时器
});

// 根据选中的group过滤二级分类选项
const filteredNameOptions = computed(() => {
  return state.selectedGroup
    ? state.nameOptions.filter(option => option.group === state.selectedGroup)
    : [];
})

// 对话框中根据选中的group过滤二级分类选项
const filteredDialogNameOptions = computed(() => {
  return state.currentTag.group
    ? state.nameOptions.filter(option => option.group === state.currentTag.group)
    : [];
})

// 获取所有分类数据
const fetchCategories = async () => {
  try {
    const res = await tagApi().getCategories()
    const categories = res.data.data as Category[];

    // 提取一级分类（去重）
    const groups = Array.from(new Set(categories.map(c => c.group)))
      .map(group => ({ value: group, label: group }));

    // 提取二级分类
    const names = categories.map(c => ({
      value: c.name,
      label: c.name,
      group: c.group
    }));

    state.groupOptions = groups;
    state.nameOptions = names;
  } catch (error) {
    ElMessage.error('获取分类失败')
  }
}

// 获取标签方法
const fetchTags = async () => {
  try {
    const res = await tagApi().getTags({
      name: state.selectedName,
      page: state.pagination.current,
      pageSize: state.pagination.size,
      tag: state.tag,
      description: state.description,
      group: state.selectedGroup
    })
    state.tags = res.data.data
    state.pagination.total = res.data.pagination.total
  } catch (error) {
    ElMessage.error('获取标签失败')
  }
}

const deleteFilter = async ()=>{
  try {
    await ElMessageBox.confirm('确定删除当前筛选的标签？', '警告', { type: 'warning' })
    const params = {
      name: state.selectedName,
      page: state.pagination.current,
      pageSize: state.pagination.size,
      tag: state.tag,
      description: state.description,
      group: state.selectedGroup
    }
    tagApi().deleteTagsByFilter(params).then(res => {
      if(res.data.success){
        ElMessage.success(JSON.stringify(res.data))
        fetchTags()
      }
      else{
        ElMessage.error(JSON.stringify(res.data))
      }
    })
  } catch (error) {
  }
}


// 分页变化处理
const handlePageChange = (page: number) => {
  state.pagination.current = page
  fetchTags()
}

const handleSizeChange = (size: number) => {
  state.pagination.size = size
  fetchTags()
}

// 筛选条件变化处理
const handleGroupFilterChange = () => {
  state.selectedName = ''; // 当一级分类变化时，重置二级分类
  state.pagination.current = 1;
  fetchTags();
}

const handleNameFilterChange = () => {
  state.pagination.current = 1;
  fetchTags();
}

// 对话框中一级分类变化处理
const handleGroupChange = () => {
  state.currentTag.name = ''; // 当一级分类变化时，重置二级分类
}

// 仅在前端添加新的一级分类（不调用接口）
const addNewGroup = () => {
  const groupName = newGroupName.value.trim();

  // 验证
  if (!groupName) {
    groupValidationMessage.value = '一级分类名称不能为空';
    return;
  }

  if (state.groupOptions.some(g => g.value === groupName)) {
    groupValidationMessage.value = '该一级分类已存在';
    return;
  }

  // 仅在前端更新选项，不调用接口
  state.groupOptions.push({ value: groupName, label: groupName });

  // 自动选中新添加的分类
  state.currentTag.group = groupName;

  // 重置状态
  newGroupName.value = '';
  showNewGroupInput.value = false;
  groupValidationMessage.value = '';

  ElMessage.success('一级分类已添加到选择列表');
}

// 仅在前端添加新的二级分类（不调用接口）
const addNewName = () => {
  const groupName = state.currentTag.group;
  const name = newName.value.trim();

  // 验证
  if (!groupName) {
    nameValidationMessage.value = '请先选择一级分类';
    return;
  }

  if (!name) {
    nameValidationMessage.value = '二级分类名称不能为空';
    return;
  }

  if (state.nameOptions.some(n => n.group === groupName && n.value === name)) {
    nameValidationMessage.value = '该二级分类已存在';
    return;
  }

  // 仅在前端更新选项，不调用接口
  state.nameOptions.push({
    value: name,
    label: name,
    group: groupName
  });

  // 自动选中新添加的分类
  state.currentTag.name = name;

  // 重置状态
  newName.value = '';
  showNewNameInput.value = false;
  nameValidationMessage.value = '';

  ElMessage.success('二级分类已添加到选择列表');
}

// 打开新增对话框
const handleAddTag = () => {
  // 重置对话框状态
  state.currentTag = {
    group:  state.selectedGroup,
    name: state.selectedName,
    value: '',
    label: '',
    type: 'add'
  };

  // 重置新增分类相关状态
  resetCategoryInputStates();
  state.dialogTitle = '新增标签';
  state.dialogVisible = true;
}

const handleAddTagByMenu = (parentTag?: Tag) => {
  // 重置对话框状态
  state.currentTag = {
    group: parentTag?.group || state.selectedGroup,
    name: parentTag?.name || state.selectedName,
    value: '',
    label: '',
    type: 'add'
  };

  // 重置新增分类相关状态
  resetCategoryInputStates();
  state.dialogTitle = '新增标签';
  state.dialogVisible = true;
}

// 重置分类输入状态
const resetCategoryInputStates = () => {
  showNewGroupInput.value = false;
  showNewNameInput.value = false;
  newGroupName.value = '';
  newName.value = '';
  groupValidationMessage.value = '';
  nameValidationMessage.value = '';
}

// 提交标签表单
const handleSubmitTag = async () => {
  // 简单验证
  if (!state.currentTag.group) {
    ElMessage.error('请选择或创建一级分类');
    return;
  }

  if (!state.currentTag.name) {
    ElMessage.error('请选择或创建二级分类');
    return;
  }

  if (!state.currentTag.value) {
    ElMessage.error('请输入标签值');
    return;
  }

  try {
    if (state.currentTag.type == 'edit') {
      // 更新标签
      const data = {
        groupId: state.currentTag.groupId,
        group: state.currentTag.group,
        name: state.currentTag.name,
        newTag: state.currentTag.value,
        oldTag: state.currentTag.oldTag,
        description: state.currentTag.label
      }
      const res = await tagApi().updateTag(data)
      if (res.status == 200) {
        ElMessage.success('修改成功')
        state.dialogVisible = false
        fetchTags()
      }
    }
    else if (state.currentTag.type == 'add'){
      const data = {
        group: state.currentTag.group,
        name: state.currentTag.name,
        tag: state.currentTag.value,
        description: state.currentTag.label
      }
      const res = await tagApi().addTag(data)
      if (res.status == 200) {
        state.dialogVisible = false
        ElMessage.success('添加成功')
        fetchTags()
        fetchCategories()
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 右键菜单处理
const onContextmenu = (tag: Tag, e: MouseEvent) => {
  const { clientX, clientY } = e
  state.dropdown.x = clientX
  state.dropdown.y = clientY
  contextmenuRef.value.openContextmenu(tag)
}

// 菜单项点击处理
const onCurrentContextmenuClick = async ({ menuItem, contextItem }) => {
  switch (menuItem.action) {
    case 'edit':
      state.currentTag = { ...contextItem };
      state.currentTag.type = 'edit'
      state.currentTag.oldTag = contextItem.value
      state.dialogTitle = '编辑标签'
      state.dialogVisible = true
      break

    case 'delete':
      try {
        await ElMessageBox.confirm('确定删除该标签？', '警告', { type: 'warning' })
        await tagApi().deleteTag(contextItem)
        ElMessage.success('删除成功')
        fetchTags()
      } catch (error) {
        // 用户取消不处理
      }
      break

    case 'add':
      handleAddTagByMenu(contextItem)
      break

    case 'copy':
      try {
        // 构建复制内容
        const copyContent = JSON.stringify({
          group: contextItem.group,
          name: contextItem.name,
          value: contextItem.value,
          label: contextItem.label
        }, null, 2)

        await navigator.clipboard.writeText(copyContent)
        ElMessage.success('标签已复制到剪贴板')
      } catch (err) {
        ElMessage.error('复制失败，请检查浏览器权限')
        console.error('复制操作失败:', err)
      }
      break
  }
}

// 直接操作函数
const handleEdit = (tag: Tag) => {
  state.currentTag = { ...tag };
  state.currentTag.type ='edit'
  state.currentTag.oldTag = tag.value
  resetCategoryInputStates();
  state.dialogTitle = '编辑标签'
  state.dialogVisible = true
}

const handleCopy = (tag: Tag) => {
  try {
    const copyContent = JSON.stringify({
      group: tag.group,
      name: tag.name,
      value: tag.value,
      label: tag.label
    }, null, 2)

    navigator.clipboard.writeText(copyContent)
    ElMessage.success('标签已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

const handleDelete = async (tag: Tag) => {
  try {
    await ElMessageBox.confirm(`确定删除标签 "${tag.group}/${tag.name}"?`, '警告', { type: 'warning' })
    await tagApi().deleteTag(tag)
    ElMessage.success('删除成功')
    fetchTags()
  } catch (error) {
    // 用户取消不处理
  }
}

// 导出处理
const handleExport = async () => {
  try {
    taskStatus.type = 'export';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `export_${Date.now()}`;
    
    const data = {
      name: state.selectedName,
      tag: state.tag,
      description: state.description,
      group: state.selectedGroup
    };
    console.log('开始导出，任务ID:', taskStatus.taskId);
    
    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 200);
    
    // 调用导出接口
    const params = { ...data, taskId: taskStatus.taskId };
    const response = await tagApi().exportTagStream(params);
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `tags_${new Date().getTime()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    clearProgressTimer();
    await fetchTaskProgress();
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
    clearProgressTimer();
    taskStatus.progressVisible = false;
  } finally {
   // 确保最终状态重置
    if (taskStatus.progress === 100 || taskStatus.progress === -1) {
      taskStatus.loading = false;
    }
    clearProgressTimer();
  }
};


const handleImport = async (file: File) => {
  try {
    taskStatus.type = 'import';
    taskStatus.loading = true;
    taskStatus.progress = 0;
    taskStatus.progressVisible = true;
    taskStatus.taskId = `import_${Date.now()}`;
    
    // 1. 创建FormData，用于上传文件内容
    const formData = new FormData();
    formData.append('file', file); // 直接添加文件对象
    formData.append('taskId', taskStatus.taskId);
    formData.append('name', state.selectedName);
    formData.append('group', state.selectedGroup);

    // 2. 启动进度查询定时器（保持运行直到任务结束）
    taskStatus.progressTimer = setInterval(() => {
      if (taskStatus.progressVisible && taskStatus.taskId) {
        fetchTaskProgress();
      }
    }, 200);

    const res = await tagApi().importTagCsv(formData);
    
    if (res.data.success) {
      ElMessage.success('提示词导入任务已启动');
    } else {
      // 仅当接口明确返回失败时才清理
      taskStatus.progressVisible = false;
      ElMessage.error(JSON.stringify(res.data) || '导入失败');
      clearProgressTimer();
    }
    return false; // 阻止默认上传
  } catch (error) {
    ElMessage.error('导入失败');
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
    return false;
  }
};

// 统一进度查询函数（支持导入/导出）
const fetchTaskProgress = async () => {
  try {
    if (!taskStatus.taskId) return;

    const response = await translateApi().getTaskProgress(taskStatus.taskId);
    taskStatus.progress = response.data.progress;

    // 进度完成或取消时，清理定时器并隐藏进度条
    if (response.data.progress === 100 || response.data.progress === -1) {
      clearProgressTimer(); // 任务结束才停止查询
      if(taskStatus.type === 'import'){
        fetchTags();
      }
      setTimeout(() => {
        taskStatus.progressVisible = false;
        taskStatus.loading = false;
      }, 1000);
    }
  } catch (error) {
    console.error(`获取${taskStatus.type === 'import' ? '导入' : '导出'}进度失败:`, error);
    clearProgressTimer();
    taskStatus.progressVisible = false;
    taskStatus.loading = false;
  }
};

// 清除进度定时器（统一封装）
const clearProgressTimer = () => {
  if (taskStatus.progressTimer) {
    clearInterval(taskStatus.progressTimer);
    taskStatus.progressTimer = null;
  }
};

// 监听对话框关闭，重置状态
watch(() => state.dialogVisible, (newVal) => {
  if (!newVal) {
    resetCategoryInputStates();
  }
});

// 初始化加载数据
onMounted(() => {
  fetchCategories();
  fetchTags();
})

</script>

<style scoped lang="scss">
.tag-manager-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 12px;
}

.filter-section {
  margin-bottom: 10px;
}

.search-btn {
  padding: 10px 20px;
}

.add-btn {
  font-size: 18px;
  padding: 10px;
}

.tags-container {
  flex: 1;
  overflow: hidden;
  background: var(--el-bg-color);
  border-radius: 12px;
  padding: 10px;
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color-lighter);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.tags-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  max-height: calc(var(--local-mount-height) - 220px);
  overflow-y: auto;
  padding: 5px;
}

.tag-card {
  border-radius: 12px;
  background: linear-gradient(135deg, var(--el-fill-color-lighter), var(--el-fill-color));
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color);
  padding: 20px;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;

  &:hover {
    transform: translateY(-5px);
    box-shadow: var(--el-box-shadow);
    border-color: var(--el-border-color-hover);
  }
}

.tag-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.tag-group {
  font-weight: 600;
  color: var(--el-color-primary);
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 45%;
}

.tag-divider {
  margin: 0 5px;
  color: var(--el-text-color-placeholder);
}

.tag-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 45%;
}

.tag-content {
  flex: 1;
  margin-bottom: 15px;
  max-height: 120px;
  overflow-y: auto;
  padding-right: 5px;
}

.tag-value,
.tag-label {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  line-height: 1.5;
}

.value-icon,
.label-icon {
  margin-right: 8px;
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
  margin-top: 3px;
}

.tag-value span {
  font-weight: 500;
  color: var(--el-text-color-primary);
  word-break: break-all;
}

.tag-label span {
  color: var(--el-text-color-regular);
  word-break: break-all;
}

.tag-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: auto;
}

/* 分类选择器样式 */
.category-selector {
  display: flex;
  gap: 10px;
  align-items: center;
}

.add-category-btn {
  white-space: nowrap;
}

.new-category-input {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 10px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
}

.new-category-input .el-input {
  flex: 1;
}

.input-actions {
  display: flex;
  gap: 5px;
}

.validation-message {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-top: 5px;
  min-height: 18px;
}

/* 自定义滚动条样式 */
.custom-scrollbar::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
  border-radius: 10px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: var(--el-border-color);
  border-radius: 10px;
  border: 2px solid var(--el-fill-color-lighter);
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color-hover);
}

.tag-content::-webkit-scrollbar {
  width: 6px;
}

.tag-content::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
  border-radius: 3px;
}

.tag-content::-webkit-scrollbar-thumb {
  background: var(--el-border-color);
  border-radius: 3px;
}

@media (max-width: 768px) {
  .tags-grid {
    grid-template-columns: 1fr;
  }

  .category-selector {
    flex-direction: column;
    align-items: stretch;
  }

  .new-category-input {
    flex-direction: column;
    align-items: stretch;
  }

  .input-actions {
    justify-content: flex-end;
    margin-top: 5px;
  }
}

@media (max-width: 480px) {
  .tag-card {
    padding: 15px;
  }

  .tag-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .tag-divider {
    display: none;
  }

  .tag-group,
  .tag-name {
    max-width: 100%;
    white-space: normal;
  }
}
</style>
<style>
/* 全局滚动条样式 */
html::-webkit-scrollbar {
  width: 10px;
}

html::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
}

html::-webkit-scrollbar-thumb {
  background: var(--el-border-color);
  border-radius: 10px;
  border: 2px solid var(--el-fill-color-lighter);
}

html::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color-hover);
}
</style>
